06. Exercise: Polymorphism
Exercise: Polymorphism
Let's walk through an implementation of the Vehicles example that we've been discussing so you can see polymorphism in action!
Create a Vehicle class
Task Description:
Create a Vehicle
class by following the instructions bellow.
Task Feedback:
Nice work!
Create a Car class that extends the Vehicle class
Task Description:
Now, it's time to create a subclass of 'Vehicle' named Car
.
Task Feedback:
Nice work!
Create a Boat class that extends the Vehicle class
Task Description:
Now, it's time to create a subclass of 'Vehicle' named Boat
.
Task Feedback:
Nice work!
Create a Plane class that extends the Vehicle class
Task Description:
Now, it's time to create a subclass of 'Vehicle' named Plane
.
Task Feedback:
Nice work
Create a VehicleTester class
Task Description:
Finally, we will create a VehicleTester
class to see how Polymorphism works in Java.
Task Feedback:
Nice work!
Solution
ND079 C1 L3 A08b Polymorphism Solution
Your code will probably differ a little from ours because you may have created different instances of each of the classes.
Again, notice the variables have the private
access modifier to ensure they are not directly accessible, while the access modifiers for the methods are public
.
public class Vehicle {
protected String start;
protected String stop;
protected String speed;
protected String direction;
public Vehicle(String start, String stop, String speed, String direction) {
this.start = start;
this.stop = stop;
this.speed = speed;
this.direction = direction;
}
public void start() {
System.out.println(start);
}
public void stop() {
System.out.println(stop);
}
public void speed() {
System.out.println(speed);
}
public void direction() {
System.out.println(direction);
}
}
public class Car extends Vehicle {
public Car() {
// Notice we are passing our arguments into our superclass (Vehicle) constructor
super("Car start", "Car stop", "Car speed", "Car direction");
}
}
public class Boat extends Vehicle {
public Boat() {
// Notice we are passing our arguments into our superclass (Vehicle) constructor
super("Boat start", "Boat stop", "Boat speed", "Boat direction");
}
}
public class Plane extends Vehicle {
public Plane() {
// Notice we are passing our arguments into our superclass (Vehicle) constructor
super("Plane start", "Plane stop", "Plane speed", "Plane direction");
}
}
public class VehicleTester {
public static void main(String[] args) {
// We can create an array of vehicles
Vehicle[] vehicles = new Vehicle[3];
// Add a Car, Plane and Boat objects to the array
vehicles[0] = new Car();
vehicles[1] = new Plane();
vehicles[2] = new Boat();
for (int i = 0; i < vehicles.length; i++) {
Vehicle vehicle = vehicles[i];
vehicle.speed();
}
}
}